/* eslint-disable no-console */
import { createApp } from 'vue'
import App from './views/App.vue'
import { setupApp } from '~/logic/common-setup'

// Firefox `browser.tabs.executeScript()` requires scripts return a primitive value
(() => {
  console.info('[vitesse-webext] Hello world from content script')
  function highlightText(keyword: string) {

    const regex = new RegExp(keyword, 'gi');
    // const allTextNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
    console.log(document.body)
    // while (allTextNodes.nextNode()) {
    //   const textNode = allTextNodes.currentNode as any;
    //   const match = textNode.data.match(regex);
    //   if (match) {
    //     const newNode = document.createElement('span');
    //     newNode.style.backgroundColor = 'yellow'; // 你可以选择其他颜色
    //     newNode.style.padding = '2px 4px';
    //     newNode.style.borderRadius = '4px';
    //     newNode.textContent = match[0];
    //     textNode.parentNode.replaceChild(newNode, textNode.splitText(textNode.data.search(match[0])));
    //   }
    // }
  }
  // communication example: send previous tab title from background page
  chrome.runtime.onMessage.addListener((message, _sender, _sendResponse) => {

    if (message.type === 'tab-prev')
      console.log(`[vitesse-webext] Navigate from page "${message.data.title}"`)
    if (message.action === 'highlight') {
      highlightText(message.keyword);
    }
  })

  // mount component to context window
  const container = document.createElement('div')
  container.id = __NAME__
  const root = document.createElement('div')
  const styleEl = document.createElement('link')
  const shadowDOM = container.attachShadow?.({ mode: __DEV__ ? 'open' : 'closed' }) || container
  styleEl.setAttribute('rel', 'stylesheet')
  styleEl.setAttribute('href', chrome.runtime.getURL('dist/contentScripts/style.css'))
  shadowDOM.appendChild(styleEl)
  shadowDOM.appendChild(root)
  document.body.appendChild(container)
  const app = createApp(App)
  setupApp(app)
  app.mount(root)
})()
